import { defineComponent, onMounted, ref, Transition } from 'vue';
import {
  ElDescriptions,
  ElDescriptionsItem,
  ElSkeleton,
  ElDivider,
  ElSwitch,
  ElEmpty,
  ElTimeline,
  ElTimelineItem,
  ElUpload
} from 'element-plus';
import { ADrawer } from '@/components/basic/drawer';
import { Icon } from '@iconify/vue';
import DynamicTable, { TableColumn, TableController } from '@/components/core/dynamic-table';
import { DefaultService as Api } from '@/servers';
import Message from '@/components/basic/message';
import {
  Columns,
  list,
  TrackStatusMapper,
  SubTrackStatusMapper,
  quoteFormItems,
  billFormItems,
  expressFormItems
} from './order-constant.ts';
import SchemaForm from '@/components/core/schema-form/index.ts';
import { ADialogInstance } from '@/components/basic/dialog/dialog.ts';

const imgPreffix = import.meta.env.VITE_IMG_PREFFIX;

export type OrderDetailExpose = {
  init: (item: any) => void;
  closeDrawer: () => void;
};

const OrderDetail = defineComponent((props, { expose }) => {
  const drawer = ref(false);
  const Loading = ref(false);
  const active = ref(0);
  const detail = ref(); // 订单详情
  const quoteDetail = ref(); // 运费报价
  const quoteForm = ref({}); // 运费报价表单
  const quoteDialogRef = ref<ADialogInstance>();
  const billDetail = ref(); // 账单信息
  const billForm = ref({}); // 账单信息表单
  const billDialogRef = ref<ADialogInstance>();
  const expressDetail = ref(); // 物流
  const expressForm = ref({}); // 物流表单
  const expressDialogRef = ref<ADialogInstance>();
  const trackInfo = ref(); // 物流跟踪信息
  const tabs = ref(list);

  const init = async (row: any) => {
    tabs.value = list.slice(0, row.status < 3 ? 1 : row.status < 4 ? 2 : row.status < 5 ? 3 : 4);

    Api.getOrderDetail(row.id)
      .then(res => {
        detail.value = res.data;
        // 初始化橱窗
        drawer.value = true;

        const dom = document.getElementById('order-detail-drawer');
        dom?.parentElement && (dom.parentElement.className += ' pointer-events-none');
      })
      .catch(_ => {
        new Message().error('获取订单详情失败');
      });
  };

  const createLink = (url: string) => {
    url = url.trim();
    if (url) url = url.startsWith('http') ? url : `${imgPreffix}${url}`;
    return (
      <a href={url} target="_blank" class="text-blue-500">
        {url}
      </a>
    );
  };

  const closeDrawer = () => {
    // 关闭抽屉
    Loading.value = false;
    active.value = 0;
    drawer.value = false;

    quoteDetail.value = null;
    billDetail.value = null;
    expressDetail.value = null;
  };

  const chooseTab = async (index: number) => {
    Loading.value = true;
    active.value = index;
    new Promise(resolve => {
      if (index === 1) {
        const isArray = quoteDetail.value instanceof Array;
        // 获取运费报价
        !isArray &&
          Api.getOrderQuoteDetail(0, detail.value.id)
            .then(res => {
              quoteDetail.value = res.data;
            })
            .catch(_ => (quoteDetail.value = []))
            .finally(() => resolve(true));
      }
      if (index === 2) {
        const isArray = billDetail.value instanceof Array;
        !isArray &&
          Api.getOrderBillDetail(0, detail.value.id)
            .then(res => {
              billDetail.value = res.data;
            })
            .catch(_ => (billDetail.value = []))
            .finally(() => resolve(true));
      }
      if (index === 3) {
        const isArray = expressDetail.value instanceof Array;
        Promise.all([
          !isArray &&
            Api.getOrderExpressDetail(0, detail.value.id)
              .then(res => {
                expressDetail.value = res.data;
              })
              .catch(_ => (expressDetail.value = [])),
          Api.getOrderExpressTrack(detail.value.id).then(res => {
            trackInfo.value = (res.data?.[0].origin_info?.trackinfo || []).map((item: any, index: number) => {
              const { checkpoint_date: date, checkpoint_delivery_status: status } = item;
              const { location, checkpoint_delivery_substatus: substatus, tracking_detail: detail } = item;
              const type =
                index === 0
                  ? status === 'delivered'
                    ? 'success'
                    : ['undelivered', 'notfound'].includes(status)
                      ? 'danger'
                      : 'primary'
                  : 'success';
              const hollow = type === 'primary' ? true : false;
              return { location, status, substatus, date, type, detail, hollow };
            });
          })
        ]).finally(() => resolve(true));
      }
      resolve(false);
    }).finally(() => (Loading.value = false));
  };

  expose({
    init,
    closeDrawer
  });

  return () => {
    return (
      <>
        <ADrawer
          v-model={drawer.value}
          with-header={true}
          id="order-detail-drawer"
          modal={false}
          show-close={false}
          class="pointer-events-auto min-w-1000px"
        >
          {{
            header: () => {
              return (
                <TableController>
                  {{
                    left: () => (
                      <>
                        <div onClick={closeDrawer}>
                          <Icon
                            icon="ant-design:close-circle-outlined"
                            class="font-size-18px cursor-pointer text-button"
                          />
                        </div>
                        {/* 
                          设计一个底部有一个滑块盒子的标签页控制按钮
                          1. 每隔标签页是一个宽100px高36px的盒子
                          2. 有一个wrapper盒子包裹所有标签页盒子，宽度为100%，高度为36px
                          3. wrapper盒子有一个滑动的宽100px高36px子盒子，
                          4. 当鼠标浮动到每个标签页盒子时，滑块盒子会滑动到对应的位置
                        */}
                        <div class="flex justify-start flex-row relative ml-4 h-40px items-end">
                          {tabs.value.map((item, index) => {
                            return (
                              <div
                                class={
                                  'w-100px h-36px text-gray-5 flex justify-center items-center cursor-pointer transition-all-300 rounded-tl-xl rounded-tr-xl hover:w-120px hover:h-40px ' +
                                  ['bg-blue-1', 'bg-purple-1', 'bg-red-1', 'bg-orange-1'][index]
                                }
                                style={
                                  active.value === index
                                    ? {
                                        'font-weight': 'bold',
                                        width: '180px',
                                        height: '40px'
                                      }
                                    : {}
                                }
                                onClick={() => chooseTab(index)}
                              >
                                {item.name}
                              </div>
                            );
                          })}
                        </div>
                      </>
                    ),
                    right: () => (
                      <>
                        {active.value === 0 && (
                          <>
                            <a-button type="warning" plain onClick={() => {}}>
                              {{
                                default: () => 'Print PackingList',
                                icon: () => <Icon icon="ant-design:printer-outlined" />
                              }}
                            </a-button>
                            <a-button type="danger" onClick={() => {}}>
                              {{
                                default: () => 'Edit Invoice',
                                icon: () => <Icon icon="ant-design:edit-outlined" />
                              }}
                            </a-button>
                          </>
                        )}
                      </>
                    )
                  }}
                </TableController>
              );
            },
            default: () => {
              return (
                <>
                  <ElSkeleton rows={15} animated class="h-full w-full box-border" loading={Loading.value}>
                    {active.value === 0 ? (
                      <div class="w-full">
                        <ElDescriptions size="small" title="Order Info" direction="vertical" border>
                          <ElDescriptionsItem span={1} rowspan={2} width={140} label="Photo" align="center">
                            <span class="text-gray">--暂无图片--</span>
                          </ElDescriptionsItem>
                          <ElDescriptionsItem label="Username" width={300}>
                            {detail.value.member.realname}
                          </ElDescriptionsItem>
                          <ElDescriptionsItem label="OrderNo">{detail.value.orderno}</ElDescriptionsItem>
                          <ElDescriptionsItem label="Create Time">{detail.value.created_at}</ElDescriptionsItem>
                          <ElDescriptionsItem label="delivery">{detail.value.ship_at}</ElDescriptionsItem>
                          <ElDescriptionsItem label="country">{detail.value.country || '----'}</ElDescriptionsItem>
                          <ElDescriptionsItem label="Contact person">
                            {detail.value.memberBusiness?.[0]?.name || '----'}
                          </ElDescriptionsItem>
                          <ElDescriptionsItem label="Contact phone">
                            {detail.value.memberBusiness?.[0]?.tel || '----'}
                          </ElDescriptionsItem>
                        </ElDescriptions>

                        {detail.value.addressList.length && (
                          <ElDescriptions size="small" class="mt-3" title="Address" direction="vertical" border>
                            <ElDescriptionsItem width={250} label="Country">
                              {detail.value.addressList[0]?.aCountry || '----'}
                            </ElDescriptionsItem>
                            <ElDescriptionsItem label="Cont">
                              {detail.value.addressList[0]?.aCont || '----'}
                            </ElDescriptionsItem>
                            <ElDescriptionsItem width={250} label="City">
                              {detail.value.addressList[0]?.aCity || '----'}
                            </ElDescriptionsItem>
                            <ElDescriptionsItem label="Company">
                              {detail.value.addressList[0]?.companyName || '----'}
                            </ElDescriptionsItem>
                            <ElDescriptionsItem label="Email">
                              {detail.value.addressList[0]?.email || '----'}
                            </ElDescriptionsItem>
                            <ElDescriptionsItem label="Postcode">
                              {detail.value.addressList[0]?.postcode || '----'}
                            </ElDescriptionsItem>
                          </ElDescriptions>
                        )}

                        <div class="el-descriptions--small  mt-3">
                          <div class="el-descriptions__header">
                            <div class="el-descriptions__title">Order List</div>
                          </div>
                          <DynamicTable
                            class="w-full"
                            border
                            size="small"
                            data={detail.value.order_items}
                            height="100%"
                            columns={Columns as unknown as TableColumn<any>[]}
                            default-expand-all={false}
                            row-key="itemid"
                            show-overflow-tooltip
                            header-row-class-name="table-header"
                          ></DynamicTable>
                        </div>
                      </div>
                    ) : active.value === 1 ? (
                      <div class="w-full">
                        <ElDescriptions size="small" title="Order Info" direction="vertical" border>
                          <ElDescriptionsItem label="Country">
                            {detail.value.address?.companyName || '----'}
                          </ElDescriptionsItem>
                          <ElDescriptionsItem label="Phone">{detail.value.address?.tel || '----'}</ElDescriptionsItem>
                          <ElDescriptionsItem label="Postcode">
                            {detail.value.addressList[0]?.postcode || '----'}
                          </ElDescriptionsItem>
                          <ElDescriptionsItem label="Address">
                            {(detail.value.addressList[0]?.aDetail || '----') +
                              ',' +
                              (detail.value.addressList[0]?.aCity || '----') +
                              ',' +
                              (detail.value.addressList[0]?.aProvince || '----')}
                          </ElDescriptionsItem>
                        </ElDescriptions>
                        <div class="w-full">
                          <TableController>
                            {{
                              left: () => (
                                <div class="flex-cc text-blue">
                                  <Icon icon="ep:timer" class="mr-2" />
                                  <span>历史运费报价</span>
                                </div>
                              ),
                              right: () => (
                                <a-button type="primary" onClick={() => quoteDialogRef.value?.openModel()}>
                                  添加
                                </a-button>
                              )
                            }}
                          </TableController>
                          {!quoteDetail.value || !quoteDetail.value.length ? (
                            <ElEmpty description="暂无历史运费报价" />
                          ) : (
                            quoteDetail.value.map(detail => (
                              <div class="w-full">
                                <div class="w-full flex flex-row">
                                  <ElDescriptions class="w-7/8" direction="horizontal" border>
                                    <ElDescriptionsItem label="快递公司">
                                      {detail.shipCompanyName || '----'}
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="预估运费">
                                      <div class="flex flex-row justify-start items-center">
                                        <Icon icon="ant-design:dollar-circle-outlined" class="text-red" />
                                        {detail.shipCost || '----'}
                                      </div>
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="预约号">
                                      {detail.reservation || '----'}
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="发货截止">
                                      {detail.shipDate.split(',')[1] || '----'}
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="有效期">
                                      {detail.shipValidity || '----'}
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="包装形式">
                                      {detail.packTypeName || '----'}
                                    </ElDescriptionsItem>
                                    <ElDescriptionsItem label="包装数量">{detail.packNum || '----'}</ElDescriptionsItem>
                                    <ElDescriptionsItem label="包装尺寸">
                                      {detail.packInfo || '----'}
                                    </ElDescriptionsItem>
                                  </ElDescriptions>
                                  <div class="w-1/8">
                                    <div class="h-40px flex-cc">
                                      <a-button type="danger">
                                        <Icon icon="ant-design:delete-outlined" />
                                      </a-button>
                                    </div>
                                    <div class="h-40px flex-cc">
                                      <ElSwitch />
                                    </div>
                                  </div>
                                </div>
                                <ElDivider />
                              </div>
                            ))
                          )}
                        </div>
                      </div>
                    ) : active.value === 2 ? (
                      <div class="w-full">
                        <TableController>
                          {{
                            left: () => (
                              <div class="flex-cc text-blue">
                                <Icon icon="ant-design:money-collect-outlined" class="mr-2" />
                                <span>账单信息</span>
                              </div>
                            ),
                            right: () => (
                              <a-button type="primary" onClick={() => billDialogRef.value?.openModel()}>
                                添加
                              </a-button>
                            )
                          }}
                        </TableController>
                        {!billDetail.value || !billDetail.value.length ? (
                          <ElEmpty description="暂无账单信息" />
                        ) : (
                          billDetail.value.map(detail => (
                            <div class="w-full">
                              <ElDescriptions class="bill-info-table" direction="horizontal" border>
                                <ElDescriptionsItem label="订单ID">{detail.orderId || '----'}</ElDescriptionsItem>
                                <ElDescriptionsItem label="订单金额">
                                  <div class="flex flex-row justify-start items-center">
                                    <Icon icon="ant-design:dollar-circle-outlined" class="text-red" />
                                    {detail.orderAmount || '----'}
                                  </div>
                                </ElDescriptionsItem>
                                <ElDescriptionsItem label="支付总金额">
                                  <div class="flex flex-row justify-start items-center">
                                    <Icon icon="ant-design:dollar-circle-outlined" class="text-red" />
                                    {detail.payAmount || '----'}
                                  </div>
                                </ElDescriptionsItem>
                                <ElDescriptionsItem label="账单内容" span={3}>
                                  {detail.content || '----'}
                                </ElDescriptionsItem>
                              </ElDescriptions>
                              <style>
                                {`
                                .bill-info-table {
                                  .el-descriptions__body .el-descriptions__table .el-descriptions__cell {
                                    text-align: center;
                                  }
                                }
                              `}
                              </style>
                              <ElDivider />
                            </div>
                          ))
                        )}
                      </div>
                    ) : (
                      <div class="w-full">
                        <TableController>
                          {{
                            left: () => (
                              <div class="flex-cc text-blue">
                                <Icon icon="icon-park-outline:ad-product" class="mr-2" />
                                <span>物流包裹</span>
                              </div>
                            ),
                            right: () => (
                              <a-button type="primary" onClick={() => expressDialogRef.value?.openModel()}>
                                添加
                              </a-button>
                            )
                          }}
                        </TableController>
                        {!expressDetail.value || !expressDetail.value.length ? (
                          <ElEmpty description="暂无物流信息" />
                        ) : (
                          expressDetail.value.map(detail => (
                            <div class="w-full">
                              <ElDescriptions class="bill-info-table" direction="horizontal" border>
                                <ElDescriptionsItem label="订单ID">{detail.orderid || '----'}</ElDescriptionsItem>
                                <ElDescriptionsItem label="物流费用">
                                  <div class="flex flex-row justify-start items-center h-23px">
                                    <Icon icon="ant-design:dollar-circle-outlined" class="text-red" />
                                    <span>{detail.shipPrice || '----'}</span>
                                  </div>
                                </ElDescriptionsItem>
                                <ElDescriptionsItem label="物流公司">
                                  {detail.shipCompanyName || '----'}
                                </ElDescriptionsItem>
                                <ElDescriptionsItem label="物流单号">{detail.shipNumber || '----'}</ElDescriptionsItem>
                                <ElDescriptionsItem label="附件" span={3}>
                                  {/* {JSON.parse(detail.file)?.[0]?.url || '----'} */}
                                  {createLink(JSON.parse(detail.file)?.[0]?.url || '')}
                                </ElDescriptionsItem>
                              </ElDescriptions>
                              <div class="px-2 py-3">
                                <ElTimeline>
                                  {(trackInfo.value || []).map((item: any, index: number) => {
                                    return (
                                      <ElTimelineItem
                                        key={index}
                                        type={item.type}
                                        hollow={item.hollow}
                                        timestamp={item.date}
                                      >
                                        {`${item.location ? '【' + item.location + '】' : ''} ${SubTrackStatusMapper[item.substatus] || TrackStatusMapper[item.status] || '--未知--'} ${item.detail}`}
                                      </ElTimelineItem>
                                    );
                                  })}
                                </ElTimeline>
                              </div>
                              <style>
                                {`
                                .bill-info-table {
                                  .el-descriptions__body .el-descriptions__table .el-descriptions__cell {
                                    text-align: center;
                                  }
                                }
                              `}
                              </style>
                              <ElDivider />
                            </div>
                          ))
                        )}
                      </div>
                    )}
                  </ElSkeleton>
                </>
              );
            }
          }}
        </ADrawer>
        <a-dialog ref={quoteDialogRef} title="add bill" width="600" onConfirm={() => {}} draggable>
          <SchemaForm
            label-width="100px"
            formItems={quoteFormItems}
            model={quoteForm.value}
            label-position="left"
            clearFormItem
          ></SchemaForm>
        </a-dialog>
        <a-dialog ref={billDialogRef} title="add bill" width="600" onConfirm={() => {}} draggable>
          <SchemaForm
            formItems={billFormItems}
            model={billForm.value}
            label-position="left"
            clearFormItem
            label-width="100px"
          >
            {{
              file: () => (
                <>
                  <ElUpload class="w-full" drag action="" multiple>
                    <Icon class="el-icon--upload" icon="ep:upload-filled" />
                    <div class="el-upload__text">
                      Drop file here or <em>click to upload</em>
                    </div>
                  </ElUpload>
                </>
              )
            }}
          </SchemaForm>
        </a-dialog>
        <a-dialog ref={expressDialogRef} title="add bill" width="600" onConfirm={() => {}} draggable>
          <SchemaForm
            formItems={expressFormItems}
            model={expressForm.value}
            label-position="left"
            clearFormItem
            label-width="100px"
          >
            {{
              file: () => (
                <>
                  <ElUpload class="w-full" drag action="" multiple>
                    <Icon class="el-icon--upload" icon="ep:upload-filled" />
                    <div class="el-upload__text">
                      Drop file here or <em>click to upload</em>
                    </div>
                  </ElUpload>
                </>
              )
            }}
          </SchemaForm>
        </a-dialog>
        <style>
          {`
            .el-drawer__header {
              margin-bottom: 0;
            }
          `}
        </style>
      </>
    );
  };
});

export default OrderDetail;
